from flask import Flask, render_template, request
import pandas as pd
import cufflinks as cf
import plotly as py
import plotly.graph_objs as go
app = Flask(__name__)


def read_data():
    return pd.read_csv ("C:/Users/Administrator/Desktop/python_data_poor/poor.csv",
                        encoding = "utf8",
                        delimiter=",")


df = read_data()
regions_available = list(df.unique().dropna())
cf.set_config_file(offline=True, theme="ggplot")
py.offline.init_notebook_mode()

@app.route('/poor')
def poor_data() -> 'html':
    df = read_data()
    the_region = request.form["the_region_selected"]
    df1 = df.query("region=='{}'".format(the_region))
    df2 = df1.rename(
        columns={'DQ': '地区', 'YF': '月份', 'TKGYRS': '特困供养人数', 'JZGYRS': '集中供养人数', 'FSGYRS': '分散供养人数', 'QZLRS': '全自理人数',
                 'BZLRS': '半自理人数', 'QHLRS': '全护理人数',
                 'ZZJZC': '总资金支出（万元）', 'HLFZJZC': '护理费用资金支出（万元）', 'SHFZJZC': '生活费资金支出（万元）', 'BZ': '备注'}, inplace=False)
    df3 = df2.drop(columns=['ID', '备注'])
    df_summary = df3.eval('总扶贫人数 = 特困供养人数 + 集中供养人数 + 分散供养人数 + 全自理人数 + 半自理人数 + 全护理人数', inplace=False)
    data_str = df_summary.to_html(classes="movies", index=False)
    the_region = request.form["the_region_selected"]
    dfs = df_summary.query("地区=='{}'".format(the_region))
    return render_template('results2.html',
                           the_res=data_str,
                           the_select_region=regions_available)
# 交互式可视化画图
    fig = dfs.iplot(kind="bar", x="地区", y="总扶贫人数", asFigure=True)
    py.offline.plot(fig, filename="example.html",auto_open=False)
    with open("example.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    # plotly.offline.plot(data, filename='file.html')
    data_str = df_summary.to_html()
    return render_template('results2.html',
                            the_plot_all = plot_all,
                            the_res = data_str,
                            the_select_region=regions_available,
                           )








@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.run()
